<template>
	<jk-dialog
		v-model="saveDialogState"
		:title="`${!dataId ? '新增' : '编辑'}-人员`"
		:width="'800px'"
		:append-to-body="true"
		v-bind="$attrs"
		:confirm-btn-loading="confirmBtnLoading"
		:show-content-loading="showContentLoading"
		@on-confirm="onConfirmButton"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
	>
		<el-form ref="ruleForm" class="dialog-view" :model="ruleForm" :rules="rules" :show-message="false" size="medium" label-width="120px">
			<el-row>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="员工编号">
						<jk-input v-model="ruleForm.code" disabled size="medium" placeholder="自动生成" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="姓名" prop="name">
						<jk-input v-model="ruleForm.name" size="medium" placeholder="姓名" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="性别" prop="gender">
						<el-radio-group v-model="ruleForm.gender">
							<el-radio :label="1">男</el-radio>
							<el-radio :label="0">女</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="出生日期">
						<el-date-picker v-model="ruleForm.birthday" value-format="yyyy-MM-dd" size="medium" type="date" style="width: 100%" placeholder="出生日期" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="手机号">
						<jk-input v-model="ruleForm.mobile" placeholder="电话" size="medium" maxlength="11" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="办公电话">
						<jk-input v-model="ruleForm.tel" placeholder="办公电话" size="medium" maxlength="18" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="身份证号">
						<jk-input v-model="ruleForm.idCard" size="medium" placeholder="身份证号" maxlength="18" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="状态">
						<el-radio-group v-model="ruleForm.onJob">
							<el-radio :label="true">在职</el-radio>
							<el-radio :label="false">离职</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item class="margin-bottom-10" label="备注">
						<el-input v-model="ruleForm.remark" type="textarea" :rows="1" size="medium" placeholder="请输入" class="width-100-percent" />
					</el-form-item>
				</el-col>
			</el-row>
			<el-tabs v-model="activeTab" type="border-card">
				<el-tab-pane name="1">
					<span slot="label"><i class="el-icon-postcard"></i> 其他信息</span>
					<el-row>
						<el-col :span="12">
							<el-form-item class="margin-bottom-10" label="部门" prop="deptId">
								<el-cascader
									v-model="ruleForm.deptId"
									filterable
									placeholder="部门"
									class="width-100-percent"
									:options="deptList"
									:props="{
										expandTrigger: 'hover',
										checkStrictly: false,
										label: 'name',
										value: 'id',
										children: 'children'
									}"
									@change="onSelectDept"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="区域" class="margin-bottom-10" prop="workshopId">
								<el-select v-model="ruleForm.workshopId" placeholder="区域" class="width-100-percent" @change="onWorkshopChange">
									<el-option v-for="item in workshopList" :key="item.id" :value="item.id" :label="item.name" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item class="margin-bottom-10" label="班组" prop="groupId">
								<el-select v-model="ruleForm.groupId" placeholder="班组" class="width-100-percent">
									<el-option v-for="item in groupList" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item class="margin-bottom-10" label="岗位" prop="postId">
								<el-select v-model="ruleForm.postId" filterable placeholder="岗位" class="width-100-percent">
									<el-option v-for="item in postList" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item class="margin-bottom-10" label="岗位编码" prop="postCode">
								<el-input v-model="ruleForm.postCode" type="textarea" :rows="1" size="medium" placeholder="请输入" class="width-100-percent" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item class="margin-bottom-10" label="直接上级" prop="leaderId">
								<el-select v-model="ruleForm.leaderId" clearable filterable placeholder="上级姓名" class="width-100-percent">
									<el-option
										v-for="item in leaderList"
										:key="item.id"
										:label="item.name"
										:value="item.id"
									/>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item class="margin-bottom-10" label="入职日期">
								<jk-date-picker v-model="ruleForm.entryTime" type="date" placeholder="入职日期" size="medium" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item class="margin-bottom-10" label="开户行">
								<jk-input v-model="ruleForm.openingBank" placeholder="开户行" size="medium" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item class="margin-bottom-10" label="银行卡号">
								<jk-input v-model="ruleForm.bankCardNumber" placeholder="银行卡号" size="medium" />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item class="margin-bottom-10" label="家庭住址">
								<jk-input v-model="ruleForm.homeAddress" placeholder="家庭住址" size="medium" />
							</el-form-item>
						</el-col>
					</el-row>
				</el-tab-pane>
				<el-tab-pane name="2">
					<span slot="label"><i class="el-icon-user"></i> 账号信息</span>
					<el-row>
						<el-col :span="24">
							<el-form-item class="margin-bottom-10" label="登录账号" prop="bindUser">
								<el-radio-group v-model="bindUser">
									<el-radio-button :label="0">无</el-radio-button>
									<el-radio-button :label="1">已有用户</el-radio-button>
									<el-radio-button :label="2">创建用户</el-radio-button>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col v-if="bindUser === 1" :span="12">
							<el-form-item v-show="bindUser === 1" class="margin-bottom-10" label="用户" prop="userId">
								<remote-search-emp-input
									v-show="bindUser === 1"
									placeholder="用户"
									only-key="userId"
									query-name="userName"
									:form-data="ruleForm"
									@on-select="onSelectEmpChange"
								></remote-search-emp-input>
							</el-form-item>
						</el-col>
						<el-col v-if="bindUser === 2" :span="12">
							<el-form-item v-show="bindUser === 2" class="margin-bottom-10" label="登录名" prop="username">
								<jk-input v-show="bindUser === 2" v-model="ruleForm.username" placeholder="登录名" class="width-100-percent" />
							</el-form-item>
						</el-col>
						<el-col v-if="bindUser === 2" :span="12">
							<el-form-item v-show="bindUser === 2" class="margin-bottom-10" label="密码" prop="password">
								<el-input v-show="bindUser === 2" v-model="ruleForm.password" placeholder="密码" class="width-100-percent" type="password" />
							</el-form-item>
						</el-col>
					</el-row>
				</el-tab-pane>
			</el-tabs>
		</el-form>
	</jk-dialog>
</template>
<script>
    import { createEmp, updateEmp, getEmp, getEmpPage } from '@/api/system/emp';
    import { listDept } from '../../../api/system/dept';
    import { createTree } from '../../../utils/jk/jk-tool';
    import { listUser } from '../../../api/system/user';
    import { validateNull, validatePhone, validateEmail, validatePassword } from '../../../utils/jk/validator';
    import calDialogHeight from '../../../mixins/cal-dialog-height';
    import { systemPostPage } from '../../../api/system/post';
    import { personnelGroupPage } from '../../../api/personnel/group';
    import { systemWorkshopPage } from '../../../api/basicData/workshop';
    import remoteSearchEmpInput from './components/remote-search-user-input';
    export default {
        components: {
            remoteSearchEmpInput
        },
        mixins: [calDialogHeight],
        inheritAttrs: false,
        props: {
            deptId: {
                type: Number,
                default: null
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: Number,
                default: null
            }
        },
        data() {
            const validate = (rule, value, callback) => value ? callback() : callback(new Error());
            return {
                activeTab: '1',
                fileList: [],
                imageId: [],
                userList: [],
                imageUrl: '',
                selectDeptArr: [],
                rawDataDeptList: [],
                workshopList: [],
                showContentLoading: false,
                saveDialogState: false,
                confirmBtnLoading: false,
                leaderList: [],
                postList: [],
                isNewUser: false,
                deptList: [],
                groupList: [],
                bindUser: 0,
                ruleForm: {
                    userId: null,
                    homeAddress: '',
                    bankCardNumber: '',
                    entryTime: '',
                    openingBank: '',
                    userName: '',
                    password: '123456',
                    groupId: null,
                    groupName: '',
                    workshopId: null,
                    workshopName: '',
                    insuranceCompany: '',
                    email: '',
                    postCode: '',
                    tel: '',
                    name: '',
                    code: '',
                    idCard: '',
                    mobile: '',
                    gender: 1,
                    birthday: '',
                    leaderId: null,
                    deptId: [],
                    deptName: '',
                    remark: '',
                    postId: null,
                    imageIds: null,
                    imageList: [],
                    onJob: true
                },
                rules: {
                    birthday: [{ required: true, validator: validateNull, trigger: 'change' }],
                    name: [{ required: true, validator: validateNull, trigger: 'change' }],
                    code: [{ required: true, validator: validateNull, trigger: 'change' }],
                    userId: [{ required: true, validator: validateNull, trigger: 'change' }],
                    idCard: [{ required: true, validator: validateNull, trigger: 'change' }],
                    mobile: [{ required: true, validator: validatePhone, trigger: 'change' }],
                    username: [{ required: true, validator: validateNull, trigger: 'change' }],
                    password: [{ required: true, validator: validatePassword, trigger: 'change' }],
                    email: [{ required: true, validator: validateEmail, trigger: 'change' }],
                    gender: [{ required: true, validator: validateNull, trigger: 'change' }],
                    deptId: [{ required: true, validator: validate, trigger: 'change' }],
                    postId: [{ required: true, validator: validateNull, trigger: 'change' }],
                    postCode: [{ required: true, validator: validateNull, trigger: 'change' }]
                }
            };
        },
        watch: {
            dialogState(newVal) {
                this.saveDialogState = newVal;
                if (newVal) {
                    if (!this.dataId) {
                        this.ruleForm.deptId = this.deptId;
                        this.selectDeptArr = [this.deptId];
                        this.ruleForm.id = null;
                    } else {
                        this.ruleForm.id = this.dataId;
                    }
                    this.getDependentData();
                } else {
                    this.imageUrl = '';
                    this.fileList = [];
                }
            }
        },
        methods: {
            onWorkshopChange() {
                this.groupList = [];
                this.$set(this.ruleForm, 'groupId', null);
                this.$set(this.ruleForm, 'groupCode', '');
                this.$set(this.ruleForm, 'groupName', '');
                this.getGroupListRequest();
            },
            onSelectEmpChange(e) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm, 'userId', e.id);
                    this.$set(this.ruleForm, 'userName', e.username);
                }
            },
            onSelectDept(e) {
                if (e.length !== 0) {
                    this.selectDeptArr = e;
                }
            },
            getDetailRequest() {
                this.showContentLoading = true;
                return getEmp(this.dataId).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res;
                        this.bindUser = res.data.res.userId ? 1 : 0;
                        if (res.data.res.account && res.data.res.account.userId) {
                            const hasEmp = this.userList.filter(x => x.id === res.data.res.account.userId).length > 0;
                            if (!hasEmp) {
                                this.userList.push({
                                    id: res.data.res.account.userId,
                                    name: res.data.res.account.username
                                });
                            }
                            // 注意大小写
                            this.$set(this.ruleForm, 'userName', res.data.res.account.username);
                        }
                        this.$set(this.ruleForm, 'password', null);
                        this.selectDeptArr = [this.ruleForm.deptId];
                        this.showContentLoading = false;
                    }
                });
            },
            getDeptListRequest() {
                return listDept({ status: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.rawDataDeptList = res.data.res || [];
                        this.deptList = createTree(res.data.res, {});
                    }
                });
            },
            getWorkshopRequest() {
                return systemWorkshopPage({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.workshopList = res.data.res || [];
                    }
                });
            },
            getEmpListRequest() {
                return getEmpPage({ onJob: this.ruleForm.onJob }).then(res => {
                    if (res.data.status === 200) {
                        this.leaderList = res.data.res || [];
                    }
                });
            },
            // 部门禁用时，不显示
            disableDept(list) {
                const arr = [];
                list.forEach(item => {
                    if (item.status === 0) {
                        arr.push(item);
                        if (item.children && item.children.length !== 0) {
                            for (let i = 0; i < item.children.length; i++) {
                                this.del(item.children);
                            }
                        }
                    } else {
                        return;
                    }
                });
                return arr;
            },
            getPostListRequest() {
                return systemPostPage({ auditState: 1, pageSize: 100 }).then(res => {
                    if (res.data.status === 200) {
                        this.postList = res.data.res || [];
                    }
                });
            },
            getGroupListRequest() {
                if (!this.ruleForm.workshopId) return;
                return personnelGroupPage({
                    auditState: 1,
                    workshopId: this.ruleForm.workshopId
                }).then(res => {
                    if (res.data.status === 200) {
                        this.groupList = res.data.res || [];
                    }
                });
            },
            getUserListRequest() {
                return listUser({ status: 1, filterBindEmp: true }).then(res => {
                    if (res.data.status === 200) {
                        this.userList = res.data.res ? res.data.res.map(x => {
                            return {
                                id: x.id,
                                name: x.username
                            };
                        }) : [];
                    }
                });
            },
            async getDependentData() {
                this.showContentLoading = true;
                await this.getEmpListRequest();
                await this.getWorkshopRequest();
                await this.getUserListRequest();
                await this.getDeptListRequest();
                await this.getPostListRequest();
                if (this.dataId) await this.getDetailRequest();
                await this.getGroupListRequest();
                this.showContentLoading = false;
            },
            onVisibleChange(e) {
                if (!e) {
                    Object.assign(this.$data.ruleForm, this.$options.data().ruleForm);
                    this.ruleForm.code = '';
                    this.activeTab = '1';
                    this.bindUser = 0;
                    this.$set(this.ruleForm, 'birthday', '');
                    this.$set(this.ruleForm, 'tel', '');
                    this.$set(this.ruleForm, 'idCard', '');
                    this.$set(this.ruleForm, 'mobile', '');
                    this.$set(this.ruleForm, 'deptId', []);
                    this.$refs['ruleForm'].resetFields();

                    this.ruleForm.onJob = true;
                }
                this.$emit('on-visible-change', e);
            },
            // 根据绑定状态，设置登录参数
            initLoginInfo() {
                if (this.bindUser === 0) {
                    this.$set(this.ruleForm, 'userId', null);
                    this.$set(this.ruleForm, 'username', '');
                    this.$set(this.ruleForm, 'password', '');
                } else if (this.bindUser === 1) {
                    this.$set(this.ruleForm, 'username', '');
                    this.$set(this.ruleForm, 'password', '');
                } else if (this.bindUser === 2) {
                    this.$set(this.ruleForm, 'userId', null);
                }
            },
            pushRequest(params) {
                if (!params.id) {
                    return createEmp(params);
                } else {
                    return updateEmp(params);
                }
            },
            saveRequest() {
                this.initLoginInfo();
                this.ruleForm.imageIds = this.imageId;
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (params.groupId) {
                    const groupItem = this.groupList.find(item => item.id === params.groupId) || {};
                    params.groupName = groupItem.name;
                }
                if (params.workshopId) {
                    const workshopItem = this.workshopList.find(item => item.id === params.workshopId) || {};
                    params.workshopCode = workshopItem.code;
                    params.workshopName = workshopItem.name;
                }
                if (params.leaderId) {
                    const leaderItem = this.leaderList.find(item => item.id === params.leaderId) || {};
                    params.leaderName = leaderItem.name;
                }
                if (params.postId) {
                    const postItem = this.postList.find(item => item.id === params.postId) || {};
                    params.postName = postItem.name;
                }
                params.account = {
                    'password': params.password,
                    'userId': params.userId,
                    'username': params.username
                };
                delete params.password;
                delete params.userId;
                delete params.username;

                if (this.selectDeptArr.length !== 0) {
                    params.deptId = this.selectDeptArr[this.selectDeptArr.length - 1];
                    params.deptName = this.rawDataDeptList.find(item => item.id === params.deptId) ? this.rawDataDeptList.find(item => item.id === params.deptId).name : '';
                }

                this.confirmBtnLoading = true;
                this.pushRequest(params).then(res => {
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.confirmBtnLoading = false;
                        this.$refs['ruleForm'].resetFields();
                        this.$emit('on-confirm');
                    } else {
                        this.confirmBtnLoading = false;
                    }
                });
            },
            onConfirmButton() {
                this.$refs['ruleForm'].validate((valid) => {
                    if (valid) {
                        this.saveRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            }
        }
    };
</script>
<style scoped lang="scss">
</style>
